package com.alinesno.cloud.monitor.agent.collect;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.monitor.agent.aspect.BaseAspect;
import com.alinesno.cloud.monitor.agent.dto.system.SystemStatusDto;
import com.alinesno.cloud.monitor.agent.tool.IPUtils;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;

/**
 * 状态上报系统
 * 
 * @author WeiXiaoJin
 * @since 2020年1月25日 下午19:45:08
 */

@Component
public class WatcherStatusHeartbeatReport extends BaseAspect implements InitializingBean, DisposableBean {

	private static final Logger log = LoggerFactory.getLogger(WatcherStatusHeartbeatReport.class);

	private String buildSystemStatus() {
		SystemStatusDto  status = new SystemStatusDto ();
		try {
			status.copyTo() ;
			status.setHostname(IPUtils.HOSTNAME);
			status.setIp(IPUtils.IP);
			status.setApplicationName(applicationName);
			
			return JSONObject.toJSONString(status) ;
		} catch (Exception e) {
			e.printStackTrace();
		} 	
		return null ; 
	}

	/*
	 * 定时将系统运行状态上报监控系统
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		CronUtil.schedule( WATCHER_STATUS_REPORT_RATE_TIME , new Task() {
		    @Override
		    public void execute() {
				log.info(Thread.currentThread().getName() + " : task run");

				String systemMessage = buildSystemStatus();
				if(StringUtils.isNoneBlank(systemMessage)) {
					kafkaProducer.asyncSendMessage(WATCHER_TOPIC_SYSTEM_MONITOR, systemMessage);
				}
		    }
		});

		// 支持秒级别定时任务
		CronUtil.setMatchSecond(true);
		CronUtil.start();
	}

	@Override
	public void destroy() throws Exception {
		
	}
}
